package com.bestcem.xm.component.mybatis.resolver;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bestcem.xm.component.mybatis.constants.MybatisConstant;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.core.MethodParameter;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

@Slf4j
public class PageArgumentResolver implements HandlerMethodArgumentResolver {

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().equals(Page.class);
    }

    @Override
    public Object resolveArgument(@NotNull MethodParameter parameter, ModelAndViewContainer mavContainer,
                                  NativeWebRequest webRequest, WebDataBinderFactory binderFactory) {

        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);

        assert request != null;
        String current = request.getParameter(MybatisConstant.PAGE_KEY);
        String size = request.getParameter(MybatisConstant.ROWSPERPAGE_KEY);

        Page<?> page = new Page<>();
        if (StringUtils.hasText(current)) {
            page.setCurrent(Long.parseLong(current));
        }

        if (StringUtils.hasText(size)) {
            page.setSize(Long.parseLong(size));
        }
        return page;
    }
}
